package cn.passlink.bletoothchat.mActivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.passlink.bletoothchat.Adapter.SendMessageAdapter;
import cn.passlink.bletoothchat.Entity.SendMessage;
import cn.passlink.bletoothchat.Entity.mUser;
import cn.passlink.bletoothchat.R;
import cn.passlink.bletoothchat.SqlTables.MessageTableManager;
import cn.passlink.bletoothchat.SqlTables.MyDatabaseHelper;

public class GroupTalkingActivity extends AppCompatActivity {
    private SQLiteDatabase database;
    private MyDatabaseHelper databaseHelper;
    private Context mcontext;
    private  SendMessageAdapter adapter;
    private  List<SendMessage> messageList = new ArrayList<SendMessage>();
    private MessageTableManager mMessageTableManager;
    private  String whoName;
    private   String whoID;
    private mUser Mainuser;
    private  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private  EditText messageText;
    private  EditText effectiveText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_talking);
        ListView listView = findViewById(R.id.group_talking_listview);
        ImageView backButton = findViewById(R.id.group_talk_back_button);
        ImageView memberButton = findViewById(R.id.menbers_group);
        TextView groupName = findViewById(R.id.group_talking_name);
        Button sendBut= findViewById(R.id.send_group_message_Button);
     messageText=findViewById(R.id.send_group_message_editText);
     effectiveText=findViewById(R.id.effective_group_message_editText);

        mcontext=this;
        databaseHelper = new MyDatabaseHelper(mcontext, 2);
        database=databaseHelper.getWritableDatabase();

        Intent intent = getIntent();
        whoID = intent.getStringExtra("groupid");
        whoName = intent.getStringExtra("groupName");
        groupName.setText(whoName);
        mMessageTableManager=new MessageTableManager(database);
        Mainuser=getPhoneById(1);

        sendBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToTargetActivity(RelationshipActivity.class);

            }

        });

        memberButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToTargetActivity(GroupMembersActivity.class);

            }
        });
//发送按钮增添记录

        // 添加 SendMessage 对象到 messageList
        mMessageTableManager=new MessageTableManager(database);
        messageList=mMessageTableManager.getAllMessageBySenderAndReceiver(Mainuser.getPhone(),whoID);
        adapter = new SendMessageAdapter(mcontext, messageList);
        listView.setAdapter(adapter);
    }

    public void goToTargetActivity(Class gotoActivity) {
        Intent intent = new Intent(this, gotoActivity);
        startActivity(intent);
    }
    //获取机主号码
    public mUser getPhoneById(int id) {
        String phone = null;
        String username = null;
        String academy = null;
        String grade = null;
        String classes = null;
        String area = null;
        String position = null;

        mUser user = new mUser();
        String[] columns = null;  // 修改为 null
        String selection = "id = ?";
        String[] selectionArgs = {String.valueOf(id)};
        Cursor cursor = database.query("user", columns, selection, selectionArgs, null, null, null);
        if (cursor.moveToFirst()) {
            phone = cursor.getString(cursor.getColumnIndexOrThrow("phone"));
            username = cursor.getString(cursor.getColumnIndexOrThrow("username"));
            academy = cursor.getString(cursor.getColumnIndexOrThrow("academy"));
            grade = cursor.getString(cursor.getColumnIndexOrThrow("grade"));
            classes = cursor.getString(cursor.getColumnIndexOrThrow("classes"));
            area = cursor.getString(cursor.getColumnIndexOrThrow("area"));
            position = cursor.getString(cursor.getColumnIndexOrThrow("position"));

        }
        user.setPhone(phone);
        user.setUsername(username);
        user.setAcademy(academy);
        user.setGrade(grade);
        user.setClasses(classes);
        user.setArea(area);
        user.setPosition(position);
        cursor.close();
        return user;
    }

    private void refreshMsg(SendMessage msg){
        messageList.add( msg);
        adapter.notifyDataSetChanged();
    }

    private void saveData(){

        String message=messageText.getText().toString();
        String effective_time=effectiveText.getText().toString();

        Date nowDate = new Date();
        String nowtimeString = format.format(nowDate);

        try {
            if(Integer.parseInt(effective_time)<1){
                Toast.makeText(mcontext, "时间设置无效，必须大于或等于1，且为整数！！！！", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        catch (Exception e){
            Toast.makeText(mcontext, "时间不是整数！！", Toast.LENGTH_SHORT).show();
            return;
        }

        if(message.isEmpty() || effective_time.isEmpty()){
            Toast.makeText(mcontext, "数据不能为空！！", Toast.LENGTH_SHORT).show();
            return;
        }
        SendMessage msg=new SendMessage();
        msg.setLocation(Mainuser.getPosition());
        msg.setReceiver(whoID);
        msg.setAcademy(Mainuser.getAcademy());
        msg.setGrade(Mainuser.getGrade());
        msg.setClasses(Mainuser.getClasses());
        msg.setSender(Mainuser.getPhone());
        msg.setEffec_time(effective_time);
        msg.setMessage(message);
        msg.setSend_time( nowtimeString);
        mMessageTableManager.addMessage(msg);
        messageText.setText("");
        effectiveText.setText("");
        Toast.makeText(mcontext, "已存入数据库，连接后自动发送！！", Toast.LENGTH_SHORT).show();
        refreshMsg(msg);

    }

}